import React, { useRef, useEffect, useMemo, forwardRef, useImperativeHandle } from "react";
import { Form as AntdForm, Input, DatePicker } from "antd";
import { useDrag } from "react-dnd";
import { useMaterialDrop } from "@editor/hooks/useMaterialDrop";

import { CommonComponentProps } from "../Page/dev";
import dayjs from "dayjs";

export interface FormRef {
    submit: () => void
}

const Form: React.ForwardRefRenderFunction<FormRef, Omit<CommonComponentProps, 'ref'>> = ({ id, name, children, onFinish }, ref) => {
    const [form] = AntdForm.useForm()
    const divRef = useRef<HTMLDivElement | null>(null);
    const [_, drag] = useDrag({
        type: 'Form',
        item: {
            type: name,
            dragType: 'move',
            id
        }
    })
    const { canDrop, drop } = useMaterialDrop(['FormItem'], id)
    useEffect(() => {
        drag(divRef);
        drop(divRef);
    }, [])

    useImperativeHandle(ref, () => {
        return {
            submit: () => {
                form.submit()
            }
        }
    }, [form])


    const formItems = useMemo(() => {
        return React.Children.map(children, (item: any) => {
            return {
                label: item.props?.label,
                name: item.props?.name,
                type: item.props?.type,
                id: item.props?.id,
                rules: item.props?.rules
            }
        })
    }, [children])

    const save = async (values: any) => {
        Object.keys(values).forEach(key => {
            if (dayjs.isDayjs(values[key])) {
                values[key] = values[key].format('YYYY-MM-DD')
            }
        })
        onFinish?.(values);
    }

    return (
        <div ref={divRef} className={`w-[100%] p-[20px] min-h-[100px] ${canDrop ? 'border-[2px] border-[blue]' : 'border-[1px] border=[#000]'}`} data-component-id={id}>
            <AntdForm labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={form} onFinish={save}>
                {
                    formItems.map((item: any) => {
                        return <AntdForm.Item key={item.id} data-component-id={item.id} name={item.name} label={item.label} rules={
                            item.rules === 'required' ? [{ required: true, message: '不能为空' }] : []
                        }>
                            {item.type === 'input' && <Input />}
                            {item.type === 'date' && <DatePicker />}
                        </AntdForm.Item>
                    })
                }
            </AntdForm>
        </div>
    )
}

export default forwardRef(Form)